import 'package:flutter/material.dart';
import 'package:flutter_deer/account/widgets/withdrawal_account_item.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/util/device_utils.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/widgets/fadein_text.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/widgets/my_button.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_deer/account/models/user_bank_entity.dart';
import 'package:flutter_deer/account/iview/user_bank_iview.dart';
import 'package:flutter_deer/account/provider/user_bank_provider.dart';
import 'package:flutter_deer/account/presenter/user_bank_presenter.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';
import '../account_router.dart';

class WithdrawalAccountPage extends StatefulWidget {

  const WithdrawalAccountPage({super.key});

  @override
  _WithdrawalAccountPageState createState() => _WithdrawalAccountPageState();
}

class _WithdrawalAccountPageState extends State<WithdrawalAccountPage>  with BasePageMixin<WithdrawalAccountPage, PowerPresenter>, AutomaticKeepAliveClientMixin<WithdrawalAccountPage> implements UserBankIMvpView {

  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
  UserBankProvider provider = UserBankProvider();
  @override
  bool get wantKeepAlive => true;
  late UserBankPagePresenter userBankPagePresenter;

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    userBankPagePresenter = new UserBankPagePresenter();
    powerPresenter.requestPresenter([userBankPagePresenter]);
    return powerPresenter;
  }
  @override
  void setUserBankList(List<UserBankEntity>? userBankList){
    provider.setLoading();
    provider.setUserBankList(userBankList);
  }

  @override
  void removeUserBankSuccess(){
    userBankPagePresenter.fetchUserBankList();
    NavigatorUtils.goBack(context);
  }

  @override
  void saveUserBankSuccess(){
    Future.delayed(Duration(seconds: 1),()=>{userBankPagePresenter.fetchUserBankList()});
  }
  @override
  void saveUserBankFail(){

  }
  
  @override
  void initState() {
    super.initState();
    if(mounted) {
      Future.delayed(Duration(seconds: 1), () =>
      {
        userBankPagePresenter.fetchUserBankList()
      });
    }
  }

  @override
  void dispose() {
    // provider.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ChangeNotifierProvider<UserBankProvider>(
        create: (_) => provider,
      child: Consumer<UserBankProvider>(
          builder: (_,provider,child){
            if(provider.stateType==StateType.loading){
              return Scaffold(
                  appBar: MyAppBar(
                    centerTitle: '${DeerLocalizations.of(context)!.withdrawalAccount.nullSafe}',
                  ),
                  body: StateLayout(type: StateType.loading)
              );
            }else{
              return Scaffold(
                  appBar: MyAppBar(
                    centerTitle: '${DeerLocalizations.of(context)!.withdrawalAccount.nullSafe}',
                      actionName: '${DeerLocalizations.of(context)!.addAccount.nullSafe}',
                      onPressed: () {
                        NavigatorUtils.pushResult(context, AccountRouter.addWithdrawalAccountPage, (result) {
                          provider.setLoading();
                          userBankPagePresenter.fetchUserBankList();
                        });
                      }
                  ),
                  body: provider.userBankList!.isEmpty ? Container(
                    width: MediaQuery.of(context).size.width,
                    child: Center(
                      child: GestureDetector(
                        onTap: (){
                          NavigatorUtils.pushResult(context, AccountRouter.addWithdrawalAccountPage, (result) {
                            provider.setLoading();
                            userBankPagePresenter.fetchUserBankList();
                          });
                        },
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Device.isWeb==true?LoadAssetImage('account/bank_card',format: ImageFormat.gif,):
                            Lottie.asset('assets/lottie/bank_card.json',width: MediaQuery.of(context).size.width/3,fit: BoxFit.cover),
                            Gaps.vGap8,
                            FadeInText(text:'${DeerLocalizations.of(context)!.addWithdrawalAccountNow.nullSafe}')
                          ],
                        ),
                      ),
                    ),
                  ):
                  AnimatedList(
                      key: _listKey,
                      padding: EdgeInsets.only(top: 8.0),
                      initialItemCount: provider.userBankList!.length,
                      itemBuilder: (_, itemIndex, animation) {
                        UserBankEntity? userBank = provider.userBankList!.elementAt(itemIndex);
                        return SizeTransition(
                          axisAlignment: 1.0,
                          sizeFactor: animation,
                          child: WithdrawalAccountItem(
                            key: ObjectKey(userBank.id),
                            data: userBank,
                            onLongPress: () => _showDeleteBottomSheet(userBank),
                            useTap: false,
                          ),
                        );

                      }

                  )
              );
            }
          }
      )
    );
  }
  
  Widget sizeItem(UserBankEntity data, int index, Animation<double> animation) {

    /// item插入、移除动画 
    return SizeTransition(
      axisAlignment: 1.0,
      sizeFactor: animation,
      child: WithdrawalAccountItem(
        key: ObjectKey(data), /// 这里注意必须添加key，原因见： https://weilu.blog.csdn.net/article/details/104745624
        data: data,
        onLongPress: () => _showDeleteBottomSheet(data),
        useTap: false,
      ),
    );
  }
  
  Future<void> removeItem(String userBankId) async {
    provider.setLoading();
    userBankPagePresenter.removeUserBank(userBankId);
  }

  void _showDeleteBottomSheet(UserBankEntity userBankEntity) {
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) {
        return Material(
          child: SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                SizedBox(
                  height: 52.0,
                  child: Center(
                    child: Text(
                      '${DeerLocalizations.of(context)!.confirmUnbindingTip.nullSafe}',
                      style: TextStyles.textSize16,
                    ),
                  ),
                ),
                Gaps.line,
                MyButton(
                  minHeight: 54.0,
                  textColor: Theme.of(context).colorScheme.error,
                  text: '${DeerLocalizations.of(context)!.confirmUnbinding.nullSafe}',
                  backgroundColor: Colors.transparent,
                  onPressed: () {
                    removeItem(userBankEntity.id!);
                  },
                ),
                Gaps.line,
                MyButton(
                  minHeight: 54.0,
                  textColor: Colours.text_gray,
                  text: '${DeerLocalizations.of(context)!.cancel.nullSafe}',
                  backgroundColor: Colors.transparent,
                  onPressed: () {
                    NavigatorUtils.goBack(context);
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
